import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/',
      name: 'Layout',
      component: () => import('@/views/Layout.vue'),
      meta: { requiresAuth: true },
      redirect: '/dashboard',
      children: [
        {
          path: '/dashboard',
          name: 'Dashboard',
          component: () => import('@/views/Dashboard.vue'),
          meta: { title: '数据统计' }
        },
        {
          path: '/posts',
          name: 'Posts',
          component: () => import('@/views/Posts.vue'),
          meta: { title: '帖子管理' }
        },
        {
          path: '/posts/pending',
          name: 'PendingPosts',
          component: () => import('@/views/PendingPosts.vue'),
          meta: { title: '待审核帖子' }
        },
        {
          path: '/sightings',
          name: 'Sightings',
          component: () => import('@/views/Sightings.vue'),
          meta: { title: '线索管理' }
        },
        {
          path: '/email-config',
          name: 'EmailConfig',
          component: () => import('@/views/EmailConfig.vue'),
          meta: { title: '邮箱配置' }
        }
      ]
    }
  ],
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()

  // 如果访问登录页
  if (to.path === '/login') {
    // 如果已经有有效的登录状态，重定向到首页
    if (authStore.isLoggedIn && authStore.admin) {
      next('/')
      return
    }
    // 否则允许访问登录页
    next()
    return
  }

  // 如果路由需要认证
  if (to.meta.requiresAuth !== false) {
    if (!authStore.isLoggedIn) {
      // 未登录，跳转到登录页
      next('/login')
      return
    }

    // 如果有token但没有用户信息，尝试获取
    // 但是要避免在刚登录后立即触发（此时admin信息可能还在更新中）
    if (!authStore.admin && from.path !== '/login') {
      try {
        await authStore.fetchCurrentAdmin()
      } catch (error) {
        // 获取用户信息失败，清除登录状态并跳转到登录页
        console.error('Token验证失败:', error)
        authStore.logoutAction()
        next('/login')
        return
      }
    }
  }

  next()
})

export default router
